<?php

namespace app\common\command\task;

use app\common\exception\BusinessException;
use app\common\logic\BuildEsQuestionFormat;
use app\common\model\CourseQuestion;
use app\common\model\CourseQuestionBackground;
use Elastic\Elasticsearch\Client;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * php think cron indexEsCourseQuestionData
 */
class IndexEsCourseQuestionData
{

    /**
     * index
     * @var string
     */
    protected $index = 'learn_course_question';

    /**
     * client
     * @var Client
     */
    protected ?Client $client = null;

    /**
     * invoke
     * @throws
     */
    public function invoke()
    {
        // 获取Es客户端
        $this->client = getEsClient();

        //  执行更新
        $this->execute();
    }

    /**
     * executeItem
     * @throws DataNotFoundException
     * @throws BusinessException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    private function execute()
    {
        // 查询条件
        $time = time() - 3600;
        $where = [
            ['a_time', '>', $time],
        ];

        // 分页构建数据
        $page = 1;
        while (true) {
            $allQuestionList = app(CourseQuestion::class)->where($where)->page($page)->limit(20)->select();
            $allQuestionList = $allQuestionList->toArray();
            if (!$allQuestionList) {
                break;
            }
            foreach ($allQuestionList as $question) {
                // 解析数据
                $questionData = json_decode($question['question_data'], true);
                if (!$questionData) {
                    throw new BusinessException('解析数据失败');
                }

                // 存在题目背景需要添加
                if ($question['background_id']) {
                    $where = [['id', '=', $question['background_id']]];
                    $questionBackground = app(CourseQuestionBackground::class)->where($where)->value('value', '');
                }

                // 生成Es内容
                $text = (new BuildEsQuestionFormat($questionData, $questionBackground ?? []))->build();
                if (!$text) {
                    return;
                }
                // 添加到ES
                $this->indexQuestion($question['id'], $question['course_id'], $text);
            }
            $page++;
        }
    }

    /**
     * indexQuestion
     * @return void
     * @throws
     */
    private function indexQuestion($id, $course_id, $content)
    {
        // 添加到ES
        $params = [
            'index' => getEsIndex($this->index),
            'id' => $id,
            'body' => ['id' => $id, 'course_id' => $course_id, 'content' => $content]
        ];
        $response = $this->client->index($params);
    }
}